package com.ts.common.aspect;

import com.alibaba.fastjson.JSONArray;
import com.ts.common.constant.ConsoleConstant;
import com.ts.common.constant.SessionConstant;
import com.ts.proj.entity.SystemButtonEntity;
import com.ts.proj.entity.SystemRoleEntity;
import com.ts.proj.service.SystemButtonService;
import com.ts.proj.service.SystemMenuService;
import com.ts.proj.service.SystemRoleService;
import com.ts.util.JsonUtils;
import com.ts.util.PageData;
import com.ts.util.RightsHelper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/8/29.
 */
@Aspect
@Component
/**
 * 此切面，用于处理路由路径跳转之前的权限监测
 */
@Slf4j
public class SessionAspect {

    @Autowired
    private SystemMenuService systemMenuService;

    @Autowired
    private SystemRoleService systemRoleService;
    @Autowired
    private SystemButtonService systemButtonService;

    @Pointcut("execution(public * com.ts.proj.controller.*.*(..))")
    public void controller() {}

    @Before("controller()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //登录界面，跳过session检测
        String name = joinPoint.getSignature().getName();
        //对登录界面和退出操作，不进行权限控制
        if(name.equals("index")||name.equals("login")||name.equals("logout")||name.equals("goToRegister")){

        }else{
            HttpSession session = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();
            String username = (String) session.getAttribute(ConsoleConstant.SESSIONUSER);
            //验证成功
            if(username instanceof String){
                session.setAttribute(SessionConstant.STATE,true);
                    //获取btn权限
                String menuURL = request.getRequestURI();
                List<Integer> ids = JsonUtils.jsonToObject(session.getAttribute(ConsoleConstant.ROLEID).toString(),List.class);
                List<SystemRoleEntity> systemRoleEntityListByIds = systemRoleService.getSystemRoleEntityListByIds(ids);
                List<PageData> buttonList = new ArrayList<>();
                for(SystemRoleEntity  systemRoleEntity: systemRoleEntityListByIds){
                    String btnRights = systemRoleEntity.getBtnRights().substring(1);
                    List<SystemButtonEntity> systemButtonEntities = systemButtonService.findSystemButtonLocalQuery(menuURL.substring(1));
                    for(SystemButtonEntity systemButtonEntity : systemButtonEntities){
                        if(RightsHelper.testRights(btnRights, systemButtonEntity.getId())){
                            PageData pageData = new PageData();
                            pageData.put("buttonName", systemButtonEntity.getButtonName());
                            pageData.put("iconCls", systemButtonEntity.getIconCls());
                            pageData.put("buttonId", systemButtonEntity.getButtonId());
                            if(!buttonList.contains(pageData)){
                                buttonList.add(pageData);
                            }
                        };
                    }
                }
                session.setAttribute(ConsoleConstant.BTNRIGHTS, JSONArray.toJSONString(buttonList));
            //session不存在
            }else{
                session.setAttribute(SessionConstant.STATE,false);
                //验证成功
                if(username instanceof String){
                    session.setAttribute(SessionConstant.STATE,true);
                    //session不存在
                }else{
                    session.setAttribute(SessionConstant.STATE,false);
                    PrintWriter out = null;
                    try {
                        out = attributes.getResponse().getWriter();
                        out.println("<html>");
                        out.println("<script>");
                        out.println("window.open ('"+request.getContextPath()+"/','_top')");
                        out.println("</script>");
                        out.println("</html>");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }
        }
        log.info("class_method={}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
    }
    @After("controller()")
    public void after(JoinPoint joinPoint){
        String name = joinPoint.getSignature().getName();
        HttpSession session = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();

        session.removeAttribute(ConsoleConstant.BTNRIGHTS);
        //如果方法名为：logout，则清除session
        if("logout".equals(name)){
            session.removeAttribute(ConsoleConstant.SESSIONUSER);
            session.removeAttribute(SessionConstant.STATE);
        }
    }
}
